import { getDocumentsDetail } from '@/services/ant-design-pro/docList';
import { DislikeFilled, LikeFilled } from '@ant-design/icons';
import CanvasHighlighter from 'canvas-highlighter';
import DOMPurify from 'dompurify';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
const Article: React.FC = (props) => {
  const { commentList, setCommentList, highlighterRef, documentUuid } = props;
  //点赞modal样式
  const [operateStyle, setOperateStyle] = useState({
    top: '0px',
    left: '0px',
    display: 'none',
  });
  const [articleHTML, setArticleHTML] = useState(null); //文档内容 从后台获取的数据
  const [articleTitle, setArticleTitle] = useState(null); //文档内容 从后台获取的数据
  const isInitHtml = useRef(false); //文档内容是否初始化

  const containerRef = useRef(null); //文档容器
  const currentRangeRef = useRef({}); //当前选中的range
  const isShowCancleBtn = useRef(false); //是否显示取消评价按钮

  //初始化高亮实例
  const initHighlighter = () => {
    if (isInitHtml.current) {
      const highlighter = new CanvasHighlighter(containerRef.current);
      highlighterRef.current = highlighter;
      //鼠标抬起事件
      containerRef.current.addEventListener('mouseup', () => {
        const range = highlighter.getSelectionRange();
        //选中范围
        if (range) {
          const end = highlighter?.getSelectionPosition()?.end; //选中文本的结束位置
          let selectionRange = highlighter.getSelectionRange(); //选中范围

          //获取containerRef距离页面左上角的距离 x = left ; y = top
          const containerOffset = containerRef.current?.getBoundingClientRect();
          //点赞modal位置 因为end返回的位置是距离页面左上角的距离 所以要减去containerRef距离页面左上角的距离
          let position = {
            top: end?.top - containerOffset?.y - 10 + 'px',
            left: end?.left - containerOffset?.x - 10 + 'px',
          };
          isShowCancleBtn.current = false; //不显示取消评价按钮
          //显示点赞modal
          setOperateStyle({
            ...position,
            display: 'block',
          });
          currentRangeRef.current = {
            ...selectionRange,
            position,
          };
        } else {
          //隐藏点赞modal 防止点击其他地方也会显示点赞modal
          setOperateStyle({
            top: '0px',
            left: '0px',
            display: 'none',
          });
        }
      });
      //鼠标点击事件
      document.addEventListener('click', (event) => {
        // 通过传入点击位置获取 range id
        const id = highlighter.getRangeIdByPointer(event.pageX, event.pageY);
        if (id) {
          isShowCancleBtn.current = true; //显示取消评价按钮
          //通过id获取range信息
          const range = highlighter.getRange(id);
          let position = range?.position;
          // 显示点赞modal
          setOperateStyle({
            ...position,
            display: 'block',
          });
          currentRangeRef.current = range; //当前选中的range
        }
        //当在选中文本后 不点赞 直接点击当前选中的文本 有可能会造成点赞modal仍留在页面上 延迟后计算一次
        setTimeout(() => {
          if (!id && !highlighter.getSelectionRange()) {
            setOperateStyle({
              top: '0px',
              left: '0px',
              display: 'none',
            });
          }
        }, 100);
      });
    }
  };
  //获取到 documentUuid 后调用 获取文章内容的接口
  useEffect(() => {
    if (documentUuid) {
      getDocumentsDetail({ id: documentUuid }).then((res) => {
        if (res.code === 0) {
          //将标题里的\n\n替换成</p><p> 用来换行
          let tit = res?.data?.title
            .split('\n\n')
            .map((paragraph) => `<p>${paragraph}</p>`)
            .join('');
          let sanitizeTitle = DOMPurify.sanitize(tit); //使用DOMPurify.sanitize()方法过滤HTML字符串 防止XSS攻击

          //将内容里的\n\n替换成</p><p> 用来换行
          let con = res?.data?.system_output
            .split('\n\n')
            .map((paragraph) => `<p>${paragraph}</p>`)
            .join('');
          let sanitizeHtml = DOMPurify.sanitize(con); //使用DOMPurify.sanitize()方法过滤HTML字符串 防止XSS攻击
          setArticleTitle(sanitizeTitle); //渲染文档标题
          console.log(articleTitle);

          setArticleHTML(sanitizeHtml); //渲染文档内容

          isInitHtml.current = true; //文档内容已初始化
          initHighlighter(); //初始化高亮实例
        }
      });
    }
  }, [documentUuid]);

  //将选中的文本添加到赞和踩列表中
  const addLickData = (type: number) => {
    const range = currentRangeRef.current; //当前选中的range
    const config = range?.config; //配置项 用来修改选中文本的样式
    config.line.visible = false; // 隐藏线段
    let addContent = {
      id: range?.id,
      content: range?.text,
      idea: '',
      type,
    };
    range.type = type; //1是赞 2是踩
    const fillColor = type === 1 ? 'rgba(96, 217, 164, 0.2)' : 'rgba(245, 112, 112, 0.2)';
    config.rect.fill = fillColor;
    //有取消评价按钮的时候 是更新评价 否则是新增评价
    if (isShowCancleBtn.current) {
      let oldRange = commentList.find((item: any) => item.id === range?.id); //旧的评价
      //新旧评价类型一样 则不变 否则更新评价
      if (oldRange?.type !== range?.type) {
        highlighterRef.current?.updateRange(range); //将选中的文本更新到高亮实例中
        //将commentList里面旧类型的type改成新的type
        setCommentList((prevList) => {
          const updatedList = [...prevList];
          updatedList[updatedList.findIndex((item: any) => item.id === range?.id)] = {
            ...updatedList[updatedList.findIndex((item: any) => item.id === range?.id)],
            type: range?.type,
          };
          return updatedList;
        });
      }
    } else {
      //添加到踩列表中
      setCommentList((prevList) => {
        const updatedList = [...prevList];
        updatedList.unshift(addContent);
        return updatedList;
      });
      highlighterRef.current?.addRange(range); //将选中的文本添加到高亮实例中
    }
    //隐藏点赞modal
    setOperateStyle({
      top: '0px',
      left: '0px',
      display: 'none',
    });
  };
  //取消评价
  const cancleModal = () => {
    const range = currentRangeRef.current; //当前选中的range
    //从评论列表中删除
    setCommentList((prevList) => {
      const updatedList = [...prevList];
      updatedList.splice(
        updatedList.findIndex((item: any) => item.id === range?.id),
        1,
      );
      return updatedList;
    });
    highlighterRef.current?.deleteRange(range.id); //删除选中的文本
    //隐藏点赞modal
    setOperateStyle({
      top: '0px',
      left: '0px',
      display: 'none',
    });
  };

  return (
    <div className="evaluationDoc-left">
      <div className="commentLoading">评价中...</div>
      <div className="articleWrap">
        {/* <div className="articleTitle">
          {<div dangerouslySetInnerHTML={{ __html: articleTitle }}></div>}
        </div> */}
        <div className="articleContent" ref={containerRef}>
          <div className="operateModal" style={operateStyle}>
            <div className="operateList" onClick={() => addLickData(1)} style={{ border: 'none' }}>
              <span className="operateList-hd">
                {' '}
                <LikeFilled style={{ color: '#60D9A4' }} />
              </span>
              <span className="operateList-bd">赞</span>
            </div>
            <div className="operateList" onClick={() => addLickData(2)}>
              <span className="operateList-hd">
                {' '}
                <DislikeFilled style={{ color: '#F57070' }} />
              </span>
              <span className="operateList-bd">踩</span>
            </div>
            {isShowCancleBtn.current && (
              <div className="operateList" onClick={() => cancleModal()}>
                取消评价
              </div>
            )}
          </div>
          {<div dangerouslySetInnerHTML={{ __html: articleHTML }}></div>}
        </div>
      </div>
    </div>
  );
};

export default Article;
